package com.lorenzogao.pley.common.util


import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.os.Message
import cn.pedant.SweetAlert.SweetAlertDialog
import com.lorenzogao.pley.R


class ProgressDialogHandler @JvmOverloads constructor(private val context: Context,
                                                      private val cancelable: Boolean = false, private val mProgressCancelListener: OnProgressCancelListener? = null) : Handler() {

    private var mProgressDialog: SweetAlertDialog? = null

    init {
        initProgressDialog()
    }



    private fun initProgressDialog() {

        if (mProgressDialog == null) {

            mProgressDialog = SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE)
            mProgressDialog!!.progressHelper.barColor = Color.parseColor("#A5DC86")
            mProgressDialog!!.titleText = context.resources.getString(R.string.loading)

            if (cancelable) {

                mProgressDialog!!.cancelText = context.resources.getString(R.string.close)
                mProgressDialog!!.setCancelClickListener { sweetAlertDialog ->
                    sweetAlertDialog.cancel()
                    mProgressCancelListener?.onCancelProgress()
                }
            }
        }
    }

    fun showProgressDialog() {

        if (mProgressDialog != null && !mProgressDialog!!.isShowing) {
            mProgressDialog!!.show()
        }
    }

    fun dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog!!.dismiss()
            mProgressDialog = null
        }
    }

    override fun handleMessage(msg: Message) {
        when (msg.what) {
            SHOW_PROGRESS_DIALOG -> showProgressDialog()
            DISMISS_PROGRESS_DIALOG -> dismissProgressDialog()
        }
    }


    interface OnProgressCancelListener {

        fun onCancelProgress()
    }

    companion object {


        val SHOW_PROGRESS_DIALOG = 1
        val DISMISS_PROGRESS_DIALOG = 0
    }
}